package com.example.docking.service.impl;

import com.example.docking.dao.jindie.GenericDataItem;
import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.request.MaterialDataRequest;
import com.example.docking.dao.jindie.response.MaterialData;
import com.example.docking.dao.jindie.response.SaveData;
import com.example.docking.dao.jingxin.request.MaterialDao;
import com.example.docking.dao.jingxin.request.MaterialtaskDao;
import com.example.docking.dao.jingxin.request.SubMaterialDao;
import com.example.docking.service.MaterialService;
import com.example.docking.util.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.model.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MaterialServiceImpl implements MaterialService {
    private static final Logger logger = LoggerFactory.getLogger(MaterialServiceImpl.class);

    @Override
    public List<MaterialtaskDao> getMaterial(DataServiceImpl service, List<MaterialtaskDao> materials) throws Exception {
        Gson gson = new Gson();
        // 设置分页参数
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        MaterialDataRequest materialDataRequest = new MaterialDataRequest();
        ApiResult MaterialResult = null;
        boolean unitFound = false;

        // 调用分页查询方法获取商品数据
        MaterialResult = service.SelectDataDetail(Constants.MATERIAL_PATH, map, "");
        Type materialDataType = new TypeToken<ResponseData<GenericDataItem<MaterialData>>>() {
        }.getType();
        ResponseData<GenericDataItem<MaterialData>> responseMaterialData = gson.fromJson(MaterialResult.getBody(), materialDataType);
        if (responseMaterialData.getErrcode() == 0) {
            GenericDataItem<MaterialData> genericDataItemMaterial = responseMaterialData.getData();
            // 解析分页信息
            String count = genericDataItemMaterial.getCount();
            int countNum = Integer.valueOf(count);
            int Pagesum = pageSize;
            List<MaterialData> materialData = genericDataItemMaterial.getRows();

            List<MaterialData> allMaterialData = new ArrayList<>(materialData);
            // 如果不是最后一页，继续获取下一页数据
            while (Pagesum < countNum) {
                page++;
                map.put("page", String.valueOf(page));
                MaterialResult = service.SelectDataDetail(Constants.MATERIAL_PATH, map, "");
                responseMaterialData = gson.fromJson(MaterialResult.getBody(), materialDataType);
                if (responseMaterialData.getErrcode() == 0) {
                    genericDataItemMaterial = responseMaterialData.getData();
                    materialData = genericDataItemMaterial.getRows();
                    allMaterialData.addAll(materialData);
                    Pagesum = pageSize * page;
                } else {
                    throw new RuntimeException(responseMaterialData.getErrcode() + ":" + responseMaterialData.getDescription());
                }
            }

            for (MaterialtaskDao materialtask1 : materials) {
                unitFound = false;
                for (MaterialData MaterialData1 : allMaterialData) {
                    if (MaterialData1.getName().equals(materialtask1.getMaterialName())) {
                        materialtask1.setMaterialid(MaterialData1.getId());
                        materialtask1.setUnitid(MaterialData1.getBase_unit_id());
                        unitFound = true;
                        break;
                    }
                }
                if (!unitFound) {
                    materialDataRequest.setName(materialtask1.getMaterialName());
                    MeasureUnitServiceImpl measureUnitService = new MeasureUnitServiceImpl();
                    String unit_id = measureUnitService.getMeasureUnitId(service, materialtask1.getUnit());
                    materialtask1.setUnitid(unit_id);
                    materialDataRequest.setBase_unit_id(unit_id);
                    ApiResult insertResult = service.InsertDataOne(Constants.MATERIAL_PATH, map, materialDataRequest);
                    Type saveDataType = new TypeToken<ResponseData<SaveData>>() {
                    }.getType();
                    ResponseData<SaveData> insertResponse = gson.fromJson(insertResult.getBody(), saveDataType);
                    if (insertResponse.getErrcode() == 0) {
                        SaveData saveData = insertResponse.getData();
                        materialtask1.setMaterialid(saveData.getIds().get(0));
                    } else {
                        throw new RuntimeException(insertResponse.getErrcode() + ":" + insertResponse.getDescription());
                    }
                }
            }
        } else {
            throw new RuntimeException(responseMaterialData.getErrcode() + ":" + responseMaterialData.getDescription());
        }

        return materials;
    }

    @Override
    public ResponseData insertMaterial(DataServiceImpl service, MaterialDao material) throws Exception {
        Gson gson = new Gson();
        logger.info("敬信的请求数据：" + gson.toJson(material));
        ResponseData respData = new ResponseData();
        ResponseData<SaveData> responseData = new ResponseData<>();
        MaterialDataRequest materialDataRequest = new MaterialDataRequest();
        materialDataRequest.setName(material.getMaterialName());
        materialDataRequest.setModel(material.getSpecModel());
        materialDataRequest.setNumber(material.getPartDraw());
        materialDataRequest.setIgnore_warn(true);
        materialDataRequest.setRemark(material.getRemark());

        String manufacturingType = material.getManufacturingType();
        //1、自制 2 外购 4外协
        if (manufacturingType.equals("1")) {
            materialDataRequest.set_self_restraint(true);
        }
        //parent_id 商品类别id  默认自制
        MaterialGroupServiceImpl materialGroupService = new MaterialGroupServiceImpl();
        String group_id = materialGroupService.getMaterialGrouptId(new DataServiceImpl(), material.getPartType());
        materialDataRequest.setParent_id(group_id);

        String unit = material.getMaterialUnit();

        // 设置分页参数
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        map.put("search", material.getPartDraw());
        MeasureUnitServiceImpl measureUnitService = new MeasureUnitServiceImpl();
        String unit_id = measureUnitService.getMeasureUnitId(service, unit);
        materialDataRequest.setBase_unit_id(unit_id);

        // 调用分页查询方法获取商品数据
        ApiResult materialResult = service.SelectDataDetail(Constants.MATERIAL_PATH, map, "");
        Type materialDataType = new TypeToken<ResponseData<GenericDataItem<MaterialData>>>() {
        }.getType();
        ResponseData<GenericDataItem<MaterialData>> responseMaterialData = gson.fromJson(materialResult.getBody(), materialDataType);
        if (responseMaterialData.getErrcode() == 0) {//返回成功的
            GenericDataItem<MaterialData> genericDataItemMaterial = responseMaterialData.getData();
            // 解析分页信息
            String count = genericDataItemMaterial.getCount();
            int countNum = Integer.valueOf(count);
            int Pagesum = pageSize;
            List<MaterialData> materialData = genericDataItemMaterial.getRows();

            List<MaterialData> allMaterialData = new ArrayList<>(materialData);
            // 如果不是最后一页，继续获取下一页数据
            while (Pagesum < countNum) {
                page++;
                map.put("page", String.valueOf(page));
                materialResult = service.SelectDataDetail(Constants.MATERIAL_PATH, map, "");
                responseMaterialData = gson.fromJson(materialResult.getBody(), materialDataType);
                if (responseMaterialData.getErrcode() == 0) {
                    genericDataItemMaterial = responseMaterialData.getData();
                    materialData = genericDataItemMaterial.getRows();
                    allMaterialData.addAll(materialData);
                    Pagesum = pageSize * page;
                } else {
                    logger.info("查询出问题了");
                }
            }


            boolean materialExists = false;
            for (MaterialData materialDataItem : allMaterialData) {
                if (materialDataItem.getNumber().equals(material.getPartDraw())) {
                    logger.info("判断是否已经存在了列表的：" + materialDataItem.getName());
                    logger.info("判断是否已经存在了插入的：" + material.getMaterialName());
                    logger.info(materialDataItem.getNumber() + "=====" + material.getPartDraw());
                    materialExists = true;
                    material.setId(materialDataItem.getId());
                    materialDataRequest.setId(materialDataItem.getId()); //客户不传这个值 通过 图令号判断相等 获取
                    // 修改时，不修改商品类别，因为ERP可能手动修改了商品类别，所以不能修改覆盖掉
                    materialDataRequest.setParent_id(materialDataItem.getParent_id());
                    break;
                }
            }

            if (!materialExists) {
                logger.info("插入商品的数据：" + gson.toJson(materialDataRequest));
                ApiResult materialResult1 = service.InsertDataOne(Constants.MATERIAL_PATH, map, materialDataRequest);
                Type SaveDataType = new TypeToken<ResponseData<SaveData>>() {
                }.getType();
                responseData = gson.fromJson(materialResult1.getBody(), SaveDataType);
                if (responseData.getErrcode() == 0) {
                    logger.info("插入商品成功");
                    logger.info("Code: {}", responseData.getErrcode());
                    logger.info("Message: {}", responseData.getDescription());
                    logger.info("data: {}", responseData.getData());
                } else {
                    logger.error("保存商品信息失败. Errcode: {}, Description: {}", responseData.getErrcode(), responseData.getDescription());

                }
            } else {
                // 这里可以添加已存在时的处理逻辑，比如记录日志等
                logger.info("商品已经存在了,修改");
                logger.info("修改商品的数据：" + gson.toJson(materialDataRequest));
                ApiResult materialResult1 = service.InsertDataOne(Constants.MATERIAL_PATH, map, materialDataRequest);
                Type SaveDataType = new TypeToken<ResponseData<SaveData>>() {
                }.getType();
                responseData = gson.fromJson(materialResult1.getBody(), SaveDataType);
                if (responseData.getErrcode() == 0) {
                    logger.info("修改商品成功");
                    logger.info("Code: {}", responseData.getErrcode());
                    logger.info("Message: {}", responseData.getDescription());
                    logger.info("data: {}", responseData.getData());
                } else {
                    logger.error("保存商品信息失败. Errcode: {}, Description: {}", responseData.getErrcode(), responseData.getDescription());

                }
            }
            respData = responseData;
        } else {
            respData = responseMaterialData;
        }
        logger.info("respData=" + respData);
        return respData;
    }

    @Override
    public List<SubMaterialDao> insertMaterialSub(DataServiceImpl service, List<SubMaterialDao> subMaterial) throws Exception {
        Gson gson = new Gson();
        int page = 1;
        int pageSize = 10;
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        MaterialDataRequest materialDataRequest = new MaterialDataRequest();
        ApiResult MaterialResult = null;
        boolean unitFound = false;

        MaterialResult = service.SelectDataDetail(Constants.MATERIAL_PATH, map, "");
        Type materialDataType = new TypeToken<ResponseData<GenericDataItem<MaterialData>>>() {
        }.getType();
        ResponseData<GenericDataItem<MaterialData>> responseMaterialData = gson.fromJson(MaterialResult.getBody(), materialDataType);
        if (responseMaterialData.getErrcode() == 0) {
            GenericDataItem<MaterialData> genericDataItemMaterial = responseMaterialData.getData();
            String count = genericDataItemMaterial.getCount();
            int countNum = Integer.valueOf(count);
            int Pagesum = pageSize;
            List<MaterialData> materialData = genericDataItemMaterial.getRows();

            List<MaterialData> allMaterialData = new ArrayList<>(materialData);
            while (Pagesum < countNum) {
                page++;
                map.put("page", String.valueOf(page));
                MaterialResult = service.SelectDataDetail(Constants.MATERIAL_PATH, map, "");
                responseMaterialData = gson.fromJson(MaterialResult.getBody(), materialDataType);
                if (responseMaterialData.getErrcode() == 0) {
                    genericDataItemMaterial = responseMaterialData.getData();
                    materialData = genericDataItemMaterial.getRows();
                    allMaterialData.addAll(materialData);
                    Pagesum = pageSize * page;
                } else {
                    throw new RuntimeException(responseMaterialData.getErrcode() + ":" + responseMaterialData.getDescription());

                }
            }

            for (SubMaterialDao submaterialtask1 : subMaterial) {
                unitFound = false;
                for (MaterialData MaterialData1 : allMaterialData) {
                    if (MaterialData1.getName().equals(submaterialtask1.getSub_materialName())) {
                        submaterialtask1.setSub_material_id(MaterialData1.getId());
                        submaterialtask1.setSub_unit_id(MaterialData1.getBase_unit_id());
                        unitFound = true;
                        break;
                    }
                }
                if (!unitFound) {
                    materialDataRequest.setName(submaterialtask1.getSub_materialName());
                    MeasureUnitServiceImpl measureUnitService = new MeasureUnitServiceImpl();
                    String unit_id = measureUnitService.getMeasureUnitId(service, submaterialtask1.getSub_unit());
                    submaterialtask1.setSub_unit_id(unit_id);
                    materialDataRequest.setBase_unit_id(unit_id);
                    ApiResult insertResult = service.InsertDataOne(Constants.MATERIAL_PATH, map, materialDataRequest);
                    Type saveDataType = new TypeToken<ResponseData<SaveData>>() {
                    }.getType();
                    ResponseData<SaveData> insertResponse = gson.fromJson(insertResult.getBody(), saveDataType);
                    if (insertResponse.getErrcode() == 0) {
                        SaveData saveData = insertResponse.getData();
                        submaterialtask1.setSub_material_id(saveData.getIds().get(0));
                    } else {
                        throw new RuntimeException(responseMaterialData.getErrcode() + ":" + responseMaterialData.getDescription());
                    }
                }
            }
        } else {
            throw new RuntimeException(responseMaterialData.getErrcode() + ":" + responseMaterialData.getDescription());
        }

        return subMaterial;
    }

    @Override
    public MaterialData selectMaterial(String materialName) {
        logger.info("查询商品信息" + materialName);
        Gson gson = new Gson();
        MaterialData materialEntity = null;
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        map.put("search", materialName);
        //根据销售订单获取商品分录：
        DataServiceImpl service = new DataServiceImpl();
        ApiResult detailMateria = null;
        try {
            detailMateria = service.SelectDataList(Constants.MATERIAL_PATH, map, "");
            Type MateriaDataType = new TypeToken<ResponseData<GenericDataItem<MaterialData>>>() {
            }.getType();
            ResponseData<GenericDataItem<MaterialData>> detailMateriaData = gson.fromJson(detailMateria.getBody(), MateriaDataType);
            logger.info("查询商品信息：返回" + detailMateriaData.getErrcode());
            logger.info("查询商品信息：返回" + detailMateriaData.getDescription());
            logger.info("查询商品信息：返回" + detailMateriaData.getData());
            if (detailMateriaData.getErrcode() == 0) {
                GenericDataItem<MaterialData> genericDataItem = detailMateriaData.getData();
                List<MaterialData> materialData = genericDataItem.getRows();
                if (materialData.size() > 0) {
                    if (materialData.size() == 1) {
                        materialEntity = materialData.get(0);
                    } else {
                        for (MaterialData MaterialData1 : materialData) {
                            if (materialName.equals(MaterialData1.getNumber())) {
                                materialEntity = MaterialData1;
                                break;
                            }
                        }
                    }

                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return materialEntity;
    }

    public MaterialDataRequest insertMaterial(MaterialDataRequest materialDataRequest) {
        logger.info("不存在新增----------商品信息");
        Gson gson = new Gson();
        DataServiceImpl service = new DataServiceImpl();
        MeasureUnitServiceImpl measureUnitService = new MeasureUnitServiceImpl();
        String unit_id = null;
        int page = 1; // 初始页码
        int pageSize = 10; // 每页记录数
        HashMap<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(page));
        map.put("page_size", String.valueOf(pageSize));
        String id = null;
        try {
            unit_id = measureUnitService.getMeasureUnitId(service, "");
            materialDataRequest.setBase_unit_id(unit_id);
            materialDataRequest.setIgnore_warn(true);
            ApiResult materialResult1 = service.InsertDataOne(Constants.MATERIAL_PATH, map, materialDataRequest);
            Type SaveDataType = new TypeToken<ResponseData<SaveData>>() {
            }.getType();
            logger.info("查询没有新增 --- 插入商品");
            ResponseData<SaveData> responseData = gson.fromJson(materialResult1.getBody(), SaveDataType);
            logger.info("Code: {}", responseData.getErrcode());
            logger.info("Message: {}", responseData.getDescription());
            logger.info("data: {}", responseData.getData());
            if (responseData.getErrcode() == 0) {
                SaveData saveData = responseData.getData();
                id = saveData.getIds().get(0);
                materialDataRequest.setId(id);
            } else {
                logger.error("插入新商品失败. Errcode: {}, Description: {}", responseData.getErrcode(), responseData.getDescription());
//                            throw new RuntimeException(responseData.getErrcode() + ":" + responseData.getDescription());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return materialDataRequest;
    }
}